use std::env;
use std::fs;
use std::fs::OpenOptions;
use std::io::Write;

use egui::epaint::tessellator::Path;

pub fn read_works_file(name: &str) -> Option<String> {
    println!("curent time: {}", name);
    if !std::fs::exists(name).is_ok() {
        Some("文件不存在！");
    }
    let json_str = match fs::read_to_string(name) {
        Ok(json) => Some(json),
        Err(e) => {
            eprint!("read works from json failed: {:?}", e);
            None
        }
    };
    json_str
}

/// 将 JSON 字符串写入文件
pub fn write_works_file(json: String, mut json_name: String) -> Result<bool, String> {
    if json.is_empty() {
        return Err("JSON 字符串为空。".to_owned());
    }

    // 添加文件扩展名
    json_name.push_str(".json");

    // 获取当前路径
    let current_dir = env::current_dir().map_err(|_| "找不到当前路径！".to_owned())?;

    // 构建文件路径
    let file_path = current_dir.join(&json_name);

    // 打开或创建文件
    let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true) // 清空文件内容
        .open(&file_path)
        .map_err(|_| "无法打开或创建文件！".to_owned())?;

    // 写入 JSON 数据
    file.write_all(json.as_bytes())
        .map_err(|_| "写入文件时发生错误！".to_owned())?;

    Ok(true)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn write_json_file() {
        //文件名称  yyyy-MM
        let today_work_file_name = Local::now().format("%y-%m-%d").to_string();

        let _ = write_works_file("hello world".to_string(), today_work_file_name);
    }
}
